<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  listBorrowsForStudentsService,
  updateReturnDateService,
  updateBorrowService,
} from "@/api/borrowing.js";
import moment from "moment";
import useUserStore from "@/stores/userStore.js";
import { updatePaymentStatusService } from "@/api/fine.js";
import { updateBookService } from "@/api/books.js";

const borrowsData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);
const selectedBorrows = ref([]);
const userStore = useUserStore();
const currentUser = userStore.info;

const searchBorrow = ref({
  borrowingId: "",
  bookId: "",
  bookName: "",
  renewalStatus: "",
  paymentStatus: "",
});

const handleSizeChange = (size) => {
  pageSize.value = size;
  listBorrows();
};

const handleCurrentChange = (num) => {
  pageNum.value = num;
  listBorrows();
};

const listBorrows = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    userId: currentUser.userId,
    ...searchBorrow.value,
  };
  let result = await listBorrowsForStudentsService(params);
  total.value = result.data.total;
  borrowsData.value = result.data.records;
};

const reset = async () => {
  searchBorrow.value = {
    borrowingId: "",
    bookId: "",
    bookName: "",
    renewalStatus: "",
    paymentStatus: "",
  };
  await listBorrows();
};

const handleSelectionChange = (selection) => {
  selectedBorrows.value = selection;
};

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "未归还";
  return moment(cellValue).format("YYYY-MM-DD");
};

const statusCellStyle = ({ row, column }) => {
  if (column.property === "returnDate") {
    if (row.returnDate && moment(row.returnDate).isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else if (row.returnDate && moment(row.returnDate).isBefore(row.dueDate)) {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (!row.returnDate && moment().isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(235, 181, 99, 0.3)" }; // 黄色
    }
  } else if (column.property === "paymentStatus") {
    if (row.paymentStatus === "未缴款") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    }
  } else if (column.property === "renewalStatus") {
    if (row.renewalStatus === "可续借") {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (row.renewalStatus === "不可续借") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    }
  }
  return {};
};

const fineFormatter = (row, column, cellValue) => {
  return cellValue === null ? "无需缴款" : cellValue;
};

const updatePaymentStatus = async (fineId) => {
  try {
    let paymentStatus = "已缴款";
    ElMessageBox.confirm("确认要进行缴费操作吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      let result = await updatePaymentStatusService(fineId, paymentStatus);
      if (result.code === 0) {
        ElMessage.success("缴费成功");
        await listBorrows();
      } else {
        ElMessage.error("缴费失败");
      }
    });
  } catch (error) {
    ElMessage.error("缴费失败");
  }
};

const returnThisBook = async (row) => {
  try {
    ElMessageBox.confirm("确认要进行图书归还操作吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      let result = await updateReturnDateService(row.borrowingId);
      if (result.code === 0) {
        const updatedBook = { bookId: row.bookId, status: "未借阅" };
        await updateBookService(updatedBook);
        ElMessage.success("图书归还成功");
        await listBorrows();
      } else {
        ElMessage.error("图书归还失败");
      }
    });
  } catch (error) {
    ElMessage.error("图书归还失败");
  }
};

const updateRenewStatus = async (borrow) => {
  try {
    ElMessageBox.confirm("确认要进行续借操作吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      borrow.renewalStatus = "不可续借";
      borrow.dueDate = moment(borrow.dueDate)
        .add(30, "days")
        .format("YYYY-MM-DD");
      let result = await updateBorrowService(borrow);
      if (result.code === 0) {
        ElMessage.success("续借成功");
        await listBorrows();
      } else {
        ElMessage.error("续借失败");
      }
    });
  } catch (error) {
    ElMessage.error("续借失败");
  }
};
const confirmBatchRenew = () => {
  ElMessageBox.confirm("此操作将续借选中的借阅图书, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        if (borrow.renewalStatus === "可续借") {
          borrow.renewalStatus = "不可续借";
          borrow.dueDate = moment(borrow.dueDate)
            .add(30, "days")
            .format("YYYY-MM-DD");
          let result = await updateBorrowService(borrow);
          if (result.code === 0) {
            successCount++;
          } else {
            skipCount++;
          }
        } else {
          skipCount++;
        }
      }
      ElMessage.success(
        `批量续借成功: ${successCount} 条, 跳过: ${skipCount} 条`,
      );
      await listBorrows();
    })
    .catch(() => {
      ElMessage.info("已取消批量续借");
    });
};

const confirmBatchReturn = () => {
  ElMessageBox.confirm("此操作将归还选中的借阅图书, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        if (!borrow.returnDate) {
          let result = await updateReturnDateService(borrow.borrowingId);
          if (result.code === 0) {
            const updatedBook = { bookId: borrow.bookId, status: "未借阅" };
            await updateBookService(updatedBook);
            successCount++;
          } else {
            skipCount++;
          }
        } else {
          skipCount++;
        }
      }
      ElMessage.success(
        `批量归还成功: ${successCount} 条, 跳过: ${skipCount} 条`,
      );
      await listBorrows();
    })
    .catch(() => {
      ElMessage.info("已取消批量归还");
    });
};

const confirmBatchPayment = () => {
  ElMessageBox.confirm("此操作将缴费选中的记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        if (borrow.paymentStatus === "未缴款") {
          let paymentStatus = "已缴款";
          let result = await updatePaymentStatusService(
            borrow.fineId,
            paymentStatus,
          );
          if (result.code === 0) {
            successCount++;
          } else {
            skipCount++;
          }
          successCount++;
        } else {
          skipCount++;
        }
      }
      ElMessage.success(
        `批量缴费成功: ${successCount} 条, 跳过: ${skipCount} 条`,
      );
      await listBorrows();
    })
    .catch(() => {
      ElMessage.info("已取消批量缴费");
    });
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};

listBorrows();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchBorrow.borrowingId"
      placeholder="请输入借阅ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBorrow.bookId"
      placeholder="请输入书籍ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBorrow.bookName"
      placeholder="请输入书名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBorrow.renewalStatus"
      placeholder="请输入续借状态"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBorrow.paymentStatus"
      placeholder="请输入缴款状态"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button
        @click="confirmBatchRenew"
        type="primary"
        icon="edit"
        :disabled="selectedBorrows.length === 0"
        >批量续借</el-button
      >
      <el-button
        @click="confirmBatchPayment"
        type="danger"
        icon="delete"
        :disabled="selectedBorrows.length === 0"
        >批量缴款</el-button
      >
      <el-button
        @click="confirmBatchReturn"
        type="success"
        icon="Refresh"
        :disabled="selectedBorrows.length === 0"
        >批量归还</el-button
      >
    </div>
    <el-button @click="listBorrows" type="primary" icon="Search"
      >搜索</el-button
    >
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置</el-button
    >
  </div>

  <el-table
    :data="borrowsData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column fixed sortable prop="borrowingId" label="借阅ID" />
    <el-table-column sortable prop="bookId" label="图书ID" />
    <el-table-column sortable prop="bookName" label="书名" />
    <el-table-column
      sortable
      prop="borrowDate"
      label="借阅日期"
      :formatter="formatDate"
      width="103"
    />
    <el-table-column
      sortable
      prop="dueDate"
      label="到期日期"
      :formatter="formatDate"
      width="103"
    />
    <el-table-column
      sortable
      prop="returnDate"
      label="归还日期"
      :formatter="formatDate"
      width="103"
    />
    <el-table-column
      sortable
      prop="renewalStatus"
      label="续借状态"
      :filters="[
        { text: '可续借', value: '可续借' },
        { text: '不可续借', value: '不可续借' },
      ]"
      :filter-method="filterHandler"
    >
    </el-table-column>
    <el-table-column
      sortable
      prop="totalAmount"
      label="缴款金额"
      :formatter="fineFormatter"
    />
    <el-table-column
      sortable
      prop="paymentStatus"
      label="缴款状态"
      :formatter="fineFormatter"
      :filters="[
        { text: '已缴款', value: '已缴款' },
        { text: '未缴款', value: '未缴款' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="续借" align="center" fixed="right" width="120">
      <template #default="scope">
        <el-button
          v-if="scope.row.renewalStatus === '可续借'"
          type="primary"
          @click="updateRenewStatus(scope.row)"
          icon="edit"
        >
          续借
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="缴款" align="center" fixed="right" width="120">
      <template #default="scope">
        <el-button
          v-if="scope.row.paymentStatus === '未缴款'"
          type="danger"
          @click="updatePaymentStatus(scope.row.fineId)"
          icon="delete"
        >
          缴款
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="归还" align="center" fixed="right" width="120">
      <template #default="scope">
        <el-button
          v-if="!scope.row.returnDate"
          type="success"
          @click="returnThisBook(scope.row)"
          icon="Refresh"
        >
          归还
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />
</template>

<style scoped></style>
